#!/usr/bin/env python
# -*- coding:utf-8 -*-

from sklearn.svm import LinearSVC
import numpy as np
from tornado.web import RequestHandler
import json
import common as com
from logHandler import getLogger
from timeoutHandler import set_timeout

class SvmVo(object):
    def __init__(self, trainDataList):
        self.trainDataList = trainDataList

def dictToSvmVo(d):
    return SvmVo(d["trainDataList"])

class SvmHandler(RequestHandler):
    @set_timeout(com.timeoutTime)
    def post(self):
        try:
            jsonByte = self.request.body
            jsonStr = jsonByte.decode("utf-8")
            svmVo = json.loads(jsonStr, object_hook=dictToSvmVo)
            log = getLogger()
            log.info("开始支持向量机算法：{}".format(svmVo.__dict__))
            data_array = svmVo.trainDataList
            predictDataList = []
            for data_line in data_array:
                data_info = data_line.split("_")
                station_id = data_info[0]
                x_test = np.asarray(data_info[1], dtype=np.float32)
                x_train = np.asarray(data_info[2].split(","), dtype=np.float32)
                y_train = np.asarray(data_info[3].split(","), dtype=np.float32)
                svc = LinearSVC()
                svc.fit(x_train.reshape(x_train.size, 1), y_train.reshape(y_train.size, 1))
                y_predict = svc.predict(x_test.reshape(1, -1))
                siteData = com.SiteData(str(station_id), str(y_predict[0]))
                predictDataList.append(siteData.__dict__)
            commonResponse = com.CommonResponse(com.successCode, com.successMsg, dict([("list", predictDataList)]))
            log.info("支持向量机算法执行完毕")
        except BaseException as e:
            print("执行支持向量机算法失败：{}".format(e))
            commonResponse = com.CommonResponse(com.errorCode, "{}".format(e), dict([("list", [])]))
            log.error("支持向量机算法执行异常")
        finally:
            # 返回数据
            self.write(commonResponse.__dict__)